Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
Unable to update React.useState("") after joining all elements in array to single string

I am trying to update a React.useState("") using setDisplay in a function that takes an array of strings and joined them into a single string before setDisplay.

Without the setDisplay, I'm able to console.log() and get the joined array.

const App = () => {
  const [display, setDisplay] = React.useState("");

  const values = [];
  const onClick = (value) => {
    values.push(value);
    console.log(values) // w/o setDisplay output: ["1","2","3","4"]; w/ setDisplay output: ["1"]; ["2"]; ["3"]; ["4"];
    setDisplay(values.join(""))
  };

  return (
    <div className="p-5">
      {display}
      <NumPads data={keypress} onClick={onClick} />
      <OperatorPads data={keypress} onClick={onClick} />
    </div>
  );
};
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

setDisplay((values) => ([...values, value].join("")]))
about 4 years ago · Juan Pablo Isaza Relatório

0

  const onClick = (value) => setDisplay((dispay) => display.concat('', value));
about 4 years ago · Juan Pablo Isaza Relatório

0

The reason the console.log seems to work when you don't call setDisplay is simply because the state of the component did not change.

When you call setDisplay, you change the state, so the entire component re-renders, which causes values to reset back to an empty array.

Solution(s)

  • One way to solve this is already shown in a previous answer.

  • Another way is to wrap your values array with useRef:

    const values = useRef([]);
    

    Then access the array using values.current

  • Yet another way is to eliminate the use of values all together and change the callback to:

    const onClick = (value) => {
      setDisplay(display + value);
    };
    
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda